package com.example.myfragmentmanager.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myfragmentmanager.R;

public class MyFragment1 extends Fragment {

    private static final String TAG = "MyFragment1";

    private View root;

    private IFragmentCallback fragmentCallback;

    public void setFragmentCallback(IFragmentCallback fragmentCallback) {
        this.fragmentCallback = fragmentCallback;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        Log.d(TAG, "onAttach: ");
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取Activity传递过来的数据
        Bundle data = getArguments();
        assert data != null;
        Log.d(TAG, "onCreate: " + data.getString("message"));
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: ");
        if (root == null) {
            root = inflater.inflate(R.layout.fragment1, container, false);
        }

        Button sendBtn = root.findViewById(R.id.fragment1_btn_send);
        sendBtn.setOnClickListener(v -> {
            // 发送数据至Activity
            fragmentCallback.setDataToActivity("Hello, I'm from Fragment1~~~");
        });

        Button getBtn = root.findViewById(R.id.fragment1_btn_get);
        getBtn.setOnClickListener(v -> {
            String data = fragmentCallback.getDataFromActivity();
            Log.d(TAG, "获取数据按钮，onClick: " + data);
        });

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onViewCreated: ");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart: ");
        super.onStart();
    }

    @Override
    public void onResume() {
        Log.d(TAG, "onResume: ");
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.d(TAG, "onPause: ");
        super.onPause();
    }

    @Override
    public void onStop() {
        Log.d(TAG, "onStop: ");
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        Log.d(TAG, "onDestroyView: ");
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: ");
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        Log.d(TAG, "onDetach: ");
        super.onDetach();
    }
}
